import axios from 'axios'
import store from '@/store'
// 创建axios实例
const service = axios.create({
  baseURL: '',
  timeout: 30000,
  withCredentials: false
})

// request拦截器
service.interceptors.request.use(
  async config => {
    if (store.getters.token) {
      // await store.dispatch('user/getUserInfo').catch(() => {})
      config.headers['Authorization'] = store.getters.token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  res => {
    const data = res.data
    const code = data?.code
    if (!code || (code >= 200 && code < 300)) {
      return Promise.resolve(res.config.noInterceptor ? res : data)
    } else {
      return Promise.reject(data)
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
